package com.example.springboot.controller;


import cn.hutool.core.io.FileUtil;
import com.example.springboot.common.Result;
import com.example.springboot.controller.request.BookPageRequest;
import com.example.springboot.entity.Book;
import com.example.springboot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/book")
public class BookController {

    @Value("${ip:localhost}")
    private String ip;

    @Value("${server.port}")
    private String port;

    @Value("${reggie.imagePath}")
    private String imagePath;

    @Autowired
    private BookService bookService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping("/list")
    public Result list(){
        List<Book> list = bookService.list();
        return Result.success(list);
    }

    /**
     * 分页查询
     * @return
     */
    @GetMapping("/page")
    public Result page(BookPageRequest BookPageRequest){
        return Result.success(bookService.page(BookPageRequest));
    }
    /**
     * 新增用户
     * 前端如何把数据发送给给后台：是通过HTTP的方式，通过POST请求，把JSON数据发送给后台接口，后台接口接收到数据之后，转换成JAVA的对象，然后把Java对象，存到数据库中。
     */
    @PostMapping("/save")
    public Result save(@RequestBody Book obj){
        bookService.save(obj);
        return Result.success();
    }

    /**
     * 文件上传到本地
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/file/upload")
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String extname = originalFilename.substring(originalFilename.indexOf(".")); //获取文件扩展名
        String FileName = UUID.randomUUID().toString() + extname;
        File saveFile = new File(imagePath);
        if (!saveFile.exists()){
            saveFile.mkdirs();
        }
        if (saveFile.exists()){
            saveFile = new File((imagePath + FileName));
        }
        file.transferTo(saveFile);
        String url = "http://" + ip + ":" + port + "/api/book/file/download/" + FileName;
        return Result.success(url);
    }

    @GetMapping("/file/download/{FileName}")
    public void download(@PathVariable String FileName, HttpServletResponse response) throws IOException {
        String filePath = imagePath + FileName;
        if (!FileUtil.exist(filePath)){
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Book obj = bookService.getById(id);
        return Result.success(obj);
    }

    /**
     * 修改数据
     */
    @PutMapping("/update")
    public Result update(@RequestBody Book obj){
        bookService.update(obj);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        bookService.deleteById(id);
        return Result.success();
    }

}
